package com.df.handler;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class FastTaskHandler {
    
    private final ExternalTaskClient client;
    private final ExecutorService executorService;
    
    public FastTaskHandler(ExternalTaskClient client) {
        this.client = client;
        // 创建高性能线程池
        this.executorService = Executors.newFixedThreadPool(20);
    }
    
    @PostConstruct
    public void subscribe() {
        log.info("初始化快速任务处理器...");
        
        // 订阅所有主题，使用快速处理模式
        client.subscribe("add-data-topic")
            .handler(this::handleAddDataFast)
            .lockDuration(20000)
            .open();
            
        client.subscribe("process-data-topic")
            .handler(this::handleProcessDataFast)
            .open();
            
        client.subscribe("sql-inject-topic")
            .handler(this::handleSqlInjectFast)
            .open();
            
        client.subscribe("success-topic")
            .handler(this::handleSuccessFast)
            .open();
            
        client.subscribe("failure-topic")
            .handler(this::handleFailureFast)
            .open();
        
        log.info("快速任务处理器初始化完成，线程池大小: 20");
    }
    
    private void handleAddDataFast(ExternalTask externalTask, ExternalTaskService externalTaskService) {
        long startTime = System.currentTimeMillis();
        log.info("=== 添加数据任务开始 ===");
        log.info("任务ID: {}", externalTask.getId());
        log.info("流程实例ID: {}", externalTask.getProcessInstanceId());
        log.info("开始时间: {}", startTime);
        
        try {
            // 快速处理，减少延迟
            log.info("开始处理业务逻辑，预计耗时5秒...");
            Thread.sleep(5000); // 5秒处理时间
            long processEndTime = System.currentTimeMillis();
            log.info("业务逻辑处理完成，耗时: {}ms", processEndTime - startTime);
            
            Map<String, Object> variables = new HashMap<>();
            variables.put("addDataResult", "数据添加成功");
            variables.put("addDataTime", System.currentTimeMillis());
            variables.put("processingTime", System.currentTimeMillis() - startTime);
            variables.put("taskStartTime", startTime);
            
            externalTaskService.complete(externalTask, variables);
            
            long completeTime = System.currentTimeMillis();
            log.info("添加数据任务完成，任务ID: {}", externalTask.getId());
            log.info("总处理时间: {}ms", completeTime - startTime);
            log.info("=== 添加数据任务结束 ===");
                    
        } catch (Exception e) {
            log.error("快速处理添加数据任务失败，任务ID: {}", externalTask.getId(), e);
            externalTaskService.handleBpmnError(externalTask, "ADD_DATA_ERROR", e.getMessage());
        }
    }
    
    private void handleProcessDataFast(ExternalTask externalTask, ExternalTaskService externalTaskService) {
        long startTime = System.currentTimeMillis();
        log.info("=== 数据处理任务开始 ===");
        log.info("任务ID: {}", externalTask.getId());
        log.info("流程实例ID: {}", externalTask.getProcessInstanceId());
        log.info("开始时间: {}", startTime);
        
        // 获取上一个任务的信息
        Object addDataTime = externalTask.getVariable("addDataTime");
        Object taskStartTime = externalTask.getVariable("taskStartTime");
        if (addDataTime != null && taskStartTime != null) {
            long timeSinceLastTask = startTime - (Long) addDataTime;
            long timeSinceFirstTask = startTime - (Long) taskStartTime;
            log.info("距离上一个任务完成: {}ms", timeSinceLastTask);
            log.info("距离流程开始: {}ms", timeSinceFirstTask);
        }
        
        try {
            // 快速处理，减少延迟
            log.info("开始处理业务逻辑，预计耗时50ms...");
            Thread.sleep(50); // 50ms处理时间
            long processEndTime = System.currentTimeMillis();
            log.info("业务逻辑处理完成，耗时: {}ms", processEndTime - startTime);
            
            Map<String, Object> variables = new HashMap<>();
            variables.put("processDataResult", "数据处理成功");
            variables.put("processDataTime", System.currentTimeMillis());
            variables.put("processingTime", System.currentTimeMillis() - startTime);
            
            externalTaskService.complete(externalTask, variables);
            
            long completeTime = System.currentTimeMillis();
            log.info("数据处理任务完成，任务ID: {}", externalTask.getId());
            log.info("总处理时间: {}ms", completeTime - startTime);
            log.info("=== 数据处理任务结束 ===");
                    
        } catch (Exception e) {
            log.error("快速处理数据处理任务失败，任务ID: {}", externalTask.getId(), e);
            externalTaskService.handleBpmnError(externalTask, "PROCESS_DATA_ERROR", e.getMessage());
        }
    }
    
    private void handleSqlInjectFast(ExternalTask externalTask, ExternalTaskService externalTaskService) {
        long startTime = System.currentTimeMillis();
        log.info("快速处理SQL注入检测任务，任务ID: {}", externalTask.getId());
        
        try {
            // 快速处理，减少延迟
            Thread.sleep(30); // 只等待30ms
            
            boolean sqlInjectResult = Math.random() > 0.5;
            
            Map<String, Object> variables = new HashMap<>();
            variables.put("sqlInjectResult", sqlInjectResult);
            variables.put("sqlInjectTime", System.currentTimeMillis());
            variables.put("sqlInjectDetails", sqlInjectResult ? "未检测到SQL注入" : "检测到SQL注入风险");
            variables.put("processingTime", System.currentTimeMillis() - startTime);
            
            externalTaskService.complete(externalTask, variables);
            
            log.info("SQL注入检测任务快速完成，任务ID: {}, 结果: {}, 处理时间: {}ms", 
                    externalTask.getId(), sqlInjectResult, System.currentTimeMillis() - startTime);
                    
        } catch (Exception e) {
            log.error("快速处理SQL注入检测任务失败，任务ID: {}", externalTask.getId(), e);
            externalTaskService.handleBpmnError(externalTask, "SQL_INJECT_ERROR", e.getMessage());
        }
    }
    
    private void handleSuccessFast(ExternalTask externalTask, ExternalTaskService externalTaskService) {
        long startTime = System.currentTimeMillis();
        log.info("快速处理成功任务，任务ID: {}", externalTask.getId());
        
        try {
            // 快速处理，减少延迟
            Thread.sleep(20); // 只等待20ms
            
            Map<String, Object> variables = new HashMap<>();
            variables.put("successResult", "成功处理完成");
            variables.put("successTime", System.currentTimeMillis());
            variables.put("finalStatus", "SUCCESS");
            variables.put("processingTime", System.currentTimeMillis() - startTime);
            
            externalTaskService.complete(externalTask, variables);
            
            log.info("成功处理任务快速完成，任务ID: {}, 处理时间: {}ms", 
                    externalTask.getId(), System.currentTimeMillis() - startTime);
                    
        } catch (Exception e) {
            log.error("快速处理成功任务失败，任务ID: {}", externalTask.getId(), e);
            externalTaskService.handleBpmnError(externalTask, "SUCCESS_ERROR", e.getMessage());
        }
    }
    
    private void handleFailureFast(ExternalTask externalTask, ExternalTaskService externalTaskService) {
        long startTime = System.currentTimeMillis();
        log.info("快速处理失败任务，任务ID: {}", externalTask.getId());
        
        try {
            // 快速处理，减少延迟
            Thread.sleep(25); // 只等待25ms
            
            Map<String, Object> variables = new HashMap<>();
            variables.put("failureResult", "失败处理完成");
            variables.put("failureTime", System.currentTimeMillis());
            variables.put("finalStatus", "FAILURE");
            variables.put("errorMessage", "检测到SQL注入风险，已进行安全处理");
            variables.put("processingTime", System.currentTimeMillis() - startTime);
            
            externalTaskService.complete(externalTask, variables);
            
            log.info("失败处理任务快速完成，任务ID: {}, 处理时间: {}ms", 
                    externalTask.getId(), System.currentTimeMillis() - startTime);
                    
        } catch (Exception e) {
            log.error("快速处理失败任务失败，任务ID: {}", externalTask.getId(), e);
            externalTaskService.handleBpmnError(externalTask, "FAILURE_ERROR", e.getMessage());
        }
    }
} 